import random
import re
from info.libs.yuntongxun.sms import CCP
from flask import request, make_response, abort, jsonify, current_app, session
import logging
from info import constants
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue


@passport_blue.route('/logout', methods=["POST"])
def logout():
    """清除session中的user_id和nick_name"""
    try:
        session.pop("user_id", None)
        session.pop("nick_name", None)
        session.pop("is_admin", None)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.SESSIONERR, errmsg="登出失败")
    return jsonify(errno=RET.OK, errmsg="登出成功")


@passport_blue.route('/login', methods=["POST"])
def login():
    """
    1. 验证用户是否存在
    2. 验证密码是否正确
    3. 设置session
    """
    mobile = request.json.get("mobile")
    password = request.json.get("password")
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if not re.match(r'^1[3456789][0-9]{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号填写错误")

    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DATAERR, errmsg="查询用户失败")

    if not user or not user.check_password(password):
        return jsonify(errno=RET.DATAERR, errmsg="用户名或密码错误")

    # 设置session
    try:
        session["nick_name"] = mobile
        session["user_id"] = user.id
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.SESSIONERR, errmsg="登录失败")

    return jsonify(errno=RET.OK, errmsg="登录成功")


@passport_blue.route('/register', methods=["POST"])
def register():
    from info import rs, db
    # 获取参数mobile, sms_code, password,并验证完整性
    json_data = request.json
    mobile = json_data.get("mobile")
    sms_code = json_data.get("sms_code")
    password = json_data.get("password")
    if not all([mobile, sms_code, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    # 获取redis sms_code
    try:
        real_sms = rs.get("sms_code_" + mobile)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DATAERR, errmsg="redis获取失败")
    if not real_sms:
        return jsonify(errno=RET.DATAERR, errmsg="手机验证码已过期")

    # 验证数据合法性
    if not re.match(r"1[3456789][0-9]{9}", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号码有误")
    # 验证手机号是否注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg="手机号已注册")

    print("sms_code, real_sms:", sms_code, real_sms)
    if sms_code != real_sms:
        return jsonify(errno=RET.DATAERR, errmsg="验证码错误")

    # 验证密码格式
    if not re.match(r"\w{6,}", password):
        return jsonify(errno=RET.DATAERR, errmsg="密码格式错误")

    # 尝试提交数据库,注册
    new_user = User()
    new_user.nick_name = mobile
    new_user.mobile = mobile
    new_user.password = password

    try:
        db.session.add(new_user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 设置登录(设置session)
    try:
        session["nick_name"] = mobile
        session["user_id"] = new_user.id
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="自动登录失败")

    # 返回数据
    return jsonify(errno=RET.OK, errmsg="注册并登录成功")


@passport_blue.route('/sms_code', methods=["POST"])
def sms_code():
    from info import rs
    """
    获取参数
    从redis获取数据
    对比图像验证码的值
    对比成功，自己生成验证码
    保存验证码到redis
    发送短信
    """
    json_data = request.json
    image_code = json_data.get("image_code")
    image_code_id = json_data.get("image_code_id")
    mobile = json_data.get("mobile")

    # 验证完整性
    if not all([image_code, image_code_id, mobile]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    # 验证手机格式
    if not re.match(r"1[3456789][0-9]{9}", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号码有误")

    # 验证手机号是否注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg="手机号已注册")

    # 获取验证码(设置了过期时间,不用删除)
    try:
        real_image_code = rs.get("image_code_id_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='redis读取验证码失败')
    if not real_image_code:
        return jsonify(errno=RET.DBERR, errmsg="验证码已过期")

    # 对比图像验证码
    print("image_code, real_image_code:", image_code, real_image_code)
    if real_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg="验证码填写错误")

    # 成功则生成短信验证码
    sms_code_str = "%06d" % random.randint(0, 999999)
    print("sms:%s" % sms_code_str)
    # 发短信
    # result = CCP().send_template_sms(mobile, [sms_code_str, 5], 1)
    # if result != "000000":
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信验证码失败")
    # 存储redis
    try:
        rs.setex("sms_code_" + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code_str)
    except Exception as e:
        current_app.logger(e)
        return jsonify(errno=RET.DBERR, errmsg="redis保存保存失败")
    return jsonify(errno=RET.OK, errmsg="发送短信验证码成功")


@passport_blue.route('/image_code')
def image_code():
    # 1. 获取参数
    image_code = request.args.get("image_code_id")
    if not image_code:
        return abort(403)
    # 2. 生成图片验证码
    name, text, image_data = captcha.generate_captcha()
    # 3. 保存到redis中
    try:
        from info import rs
        rs.setex("image_code_id_" + image_code, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        logging.error(e)
        return abort(500)

    print("image_code:", text)
    response = make_response(image_data)
    response.headers["Content-Type"] = "image/jpg"

    return response
